/*
 * COAPI - Copyright (C) 2019-2020 Cocheer Tech. Co., Ltd.
 * All rights reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <smart_audio.h>
#include "coapi_logger.h"
#include "coapi_sync.h"
#include "coapi_audio.h"
#include "coapi_media.h"
#include "coapi_ota.h"
#include "coapi_timer.h"
#include "coapi_wireless.h"
#include "coapi_cmd.h"
#include "coapi_funchub.h"
#include "coapi_dev.h"
#include "coapi_devsta.h"
#include "coapi_devctrl.h"
#include "coapi_dev_ctrl.h"
#include "coapi_comm.h"
//#define CONF_COMM_DEBUG
#define TAG "coapi"

/* 播放器初始化 */
void coapi_player_start(char* toneurl, char* audiourl)
{
	if(audiourl) {
		/* 首先停止之前的音乐播放 */
		smtaudio_stop(MEDIA_MUSIC);
	}
	if(toneurl) {
		LOGD(TAG, "URLINFO: toneurl: %s", toneurl);
		smtaudio_start(MEDIA_SYSTEM, toneurl, 0, 1);
	}
	if(audiourl) {
		LOGD(TAG, "URLINFO: audiourl: %s", audiourl);
		smtaudio_start(MEDIA_MUSIC, audiourl, 0, 1);
	}
    return;
}

/* 播放下一曲 */
void coapi_player_next(void)
{
	return;
}
/* 播放上一曲 */
void coapi_player_prev(void)
{
    return;
}
/* 播放本地音源 */
int coapi_play_local_music(void)
{
	/* 默认返回0，为播放在线音乐 */
    return 0;
}
/* 媒体状态 */
int media_status(media_info* media)
{
    return 0;
}

int coapi_get_song_num(void)
{
    return smtaudio_vol_get();
}

/*
 * @brief 端云同步回调
 * @return  
 */
static void sync_callback(int cmdid, sync_item* sync)
{
	int rec = 0;
	
    if (cmdid == 0 || sync == NULL) {
		return;
	}

    /* 用于标记是否反馈或者请求云端 */
    int cbcmd = 0;

    if (cmdid & SYNC_MEDIA_PAUSE) {
		if (1) { /* 设备处于播放状态,此处需根据实际做判断修改 */
			/*通知云端设备播放器暂停 */
			coapi_media_pause();
			/* 设备执行暂停动作 */
			smtaudio_pause();
		} else {
			/*通知云端设备播放器播放 */
			coapi_media_play();
			/* 设备执行播放动作 */
			/* dev_player_play(); */
		}
    }

    if (cmdid & SYNC_MEDIA_STOP) {
		/* 通知云端播放列表会被清空 */
		coapi_media_stop();

		/* 设备执行停止播放动作 */
		smtaudio_stop(MEDIA_MUSIC);
    }

    if (cmdid & SYNC_MEDIA_PREV) {
		if (coapi_play_local_music()) {
			/* 播放的是本地内容 */
			coapi_player_prev();
		} else {
			/* 请求云端下发上一曲 */
			coapi_audio_prev();
		}
    }

    if (cmdid & SYNC_MEDIA_NEXT) {
		if (coapi_play_local_music()) {
			/* 播放的是本地内容 */
			coapi_player_next();
		} else {
			/* 请求云端下发下一曲 */
			coapi_audio_next();
		}
    }

    if (cmdid & SYNC_VOLUME_UP) {
		smtaudio_vol_up(10);
    }

    if (cmdid & SYNC_VOLUME_DOWN) {
		smtaudio_vol_down(10);
    }

    if (cmdid & SYNC_MEDIA_STATUS) {
		media_info info;
		memset(&info, 0, sizeof(media_info));
	/* 根据实际播放信息meida */
#if 0
        info.type = TYPE_AI;
        info.seq = 0;
        info.status = TYPEER_PLAY;
        info.mode = PLAY_MODE_CIRCUL;
        info.position = 60;
        info.duration = 360;
#else
		media_status(&info);
#endif
		coapi_media_start(&info);
    }

    if (cmdid & SYNC_BATTERY) {
		sync->state.battery = dev_get_battery();
		cbcmd |= SYNC_BATTERY;
    }

    if (cmdid & SYNC_CHILDLOCK) {
		/* 云端设置童锁状态 */
		if (sync->state.childlock == CHILDLOCK_OPEN) {
			rec = dev_childlock_open();
		} else if (sync->state.childlock == CHILDLOCK_CLOSE) {
			rec = dev_childlock_close();
		} else {
			/* 云端给设备端设置状态 */
			sync->state.childlock = -1;
			cbcmd |= SYNC_CHILDLOCK;
		}
    }

    if (cmdid & SYNC_STORAGE) {
		int cap_all = 0;  /* 存储总容量 */
		int cap_free = 0; /* 可用容量 */

		/* 单位是M */
		rec = dev_get_storage(&cap_all, &cap_free);
		sync->state.storage = (cap_all << 16 | cap_free);
		cbcmd |= SYNC_STORAGE;
    }

    if (cmdid & SYNC_SONG_NUM) {
		sync->state.song_num = coapi_get_song_num();
		cbcmd |= SYNC_SONG_NUM;
    }

    if (cmdid & SYNC_VOL) {
		/**
		* < 0 表示获取音量大小
		* > 0 表示设置音量大小
		* 音量等级分为: 1 —— 100
		* 可通过线性转换成实际的音量等级
		*/
		if (sync->state.volume < 0) {
			sync->state.volume = smtaudio_vol_get();
			cbcmd |= SYNC_VOL;
		} else {
			smtaudio_vol_set(sync->state.volume);
		}
    }

    if (cmdid & SYNC_CHARGE) {
		sync->state.charge = dev_get_charge();
		cbcmd |= SYNC_CHARGE;
    }

    if (cmdid & SYNC_OTA_STATUS) {
		int status = dev_ota_status();

		switch (status) {
			case OTA_SUCCESS:
				coapi_ota_success();
				break;
			case OTA_FAIL:
				coapi_ota_fail();
				break;
			case OTA_NONE:
				coapi_ota_none();
				break;
			default:
				if(status > 0 && status <= 100)
					coapi_ota_process(status);
				break;
		}
    }

    if (cmdid & SYNC_ONOFF) {
		dev_power_onoff();
    }

    if (cmdid & SYNC_FACTORY) {
		dev_factory();
    }

    if (cbcmd == 0) {
		return;
	}

    sync->cmdid = cbcmd;

#ifdef CONF_COMM_DEBUG
    xdebug("*******************************************************************"
           "******");
    xdebug("*************************** COAPI COMM INFO "
           "*****************************");
    xdebug("*******************************************************************"
           "******");

    xdebug("sync->cmdid: %d", sync->cmdid);
    xdebug("sync->status: %d", sync->status);
    xdebug("sync->json: %p", sync->json);
    xdebug("sync->state.volume: %d", sync->state.volume);
    xdebug("sync->state.childlock: %d", sync->state.childlock);
    xdebug("sync->state.battery: %d", sync->state.battery);
    xdebug("sync->state.storage: %d", sync->state.storage);
    xdebug("sync->state.song_num: %d", sync->state.song_num);
    xdebug("sync->state.charge: %d", sync->state.charge);

    xdebug("*******************************************************************"
           "******");
    xdebug("****************************** END "
           "**************************************");
    xdebug("*******************************************************************"
           "******");
#endif

    coapi_sync_cmd(cbcmd, sync);

    return;
}
/*
 * @brief 闹钟回调
 * @return  
 */
static void timer_callback(timer_info** timer, char* event, int cnt, int status,
                           int tick, unsigned char mode)
{
    if (timer == NULL) {
		return;
	}
    xdebug("cnt: %d status: %d, mode: %d, tick: %d", cnt, status, mode, tick);

    if (cnt < 0) {
		xdebug("request timer err");
		return;
    }
    if (cnt == 0) {
		xdebug("no timer");
		return;
    }
    /* 模式A */

    if (mode == TIMER_MODE_A) {
#ifdef CONF_COMM_DEBUG
		xdebug("alarmid: %s", (*timer)->alarmid);
		xdebug("date: %s", (*timer)->date);
		xdebug("time: %s", (*timer)->time);
		xdebug("toneurl: %s", (*timer)->toneurl);
		xdebug("audiourl: %s", (*timer)->audiourl);
		xdebug("wcmd: %s", (*timer)->wcmd);
		xdebug("action: %d", (*timer)->action);
		xdebug("minite: %d", (*timer)->minite);
		xdebug("nap: %d", (*timer)->nap);
		xdebug("zone: %d", (*timer)->zone);
		xdebug("eventid: %d", (*timer)->eventid);
#endif
		if(status == TIMER_RING){
			/* play (*timer)->toneurl、(*timer)->audiourl */
			coapi_player_start((*timer)->toneurl, (*timer)->audiourl);
		}
		/* 执行定时控制指令 */
		coapi_cmd_ctrl_cb((*timer)->action, (*timer)->wcmd);

    } else if (mode == TIMER_MODE_B) { /* 模式B */
		// xdebug("AAAAAA: should not enter here!");
    }

    return;
}
/*
 * @brief 无线回调
 * @return  
 */
static void wireless_callback(wireless_info* wireless, int status)
{
    if (wireless == NULL) {
	    return;
	}

#ifdef CONF_COMM_DEBUG
    xdebug("status: %d", status);
    xdebug("wireless->used: %d", wireless->used);
    xdebug("wireless->data: %s", wireless->data);
#endif

    return;
}
/*
 * @brief 音频回调
 * @return  
 */
static void audio_callback(audio_info* audio, int status)
{
    if (audio == NULL) {
	    return;
	}

#ifdef CONF_COMM_DEBUG
    xdebug("status: %d", status);
    xdebug("audio->type: %d", audio->type);
    xdebug("audio->seq: %d", audio->seq);
    xdebug("audio->toneurl: %s", audio->toneurl);
    xdebug("audio->audiourl: %s\n", audio->audiourl);
    xdebug("audio->out: %s\n", audio->out);
    xdebug("audio->chattype: %d\n", audio->chattype);
    xdebug("audio->eventid: %d\n", audio->eventid);
#endif

    switch (audio->type) {
		case TYPE_CUR:
			coapi_player_start(audio->toneurl, audio->audiourl);
			break;
		case TYPE_AI: /* 此处为AI上下曲续播，非AI语音对讲 */
			coapi_player_start(audio->toneurl, audio->audiourl);
			break;
		case TYPE_PUSH:
			coapi_player_start(audio->toneurl, audio->audiourl);
			break;
		case TYPE_DAILY:
			coapi_player_start(audio->toneurl, audio->audiourl);
			break;
		case TYPE_FMLYCHAT:
			switch	(audio->chattype) {
				case CHAT_TYPE_TEXT:
					xdebug("文字信息");
					break;
				case CHAT_TYPE_AUDIO:
					xdebug("语音信息");
					coapi_player_start(audio->toneurl, audio->audiourl);
					break;
				case CHAT_TYPE_PIC:
					xdebug("图片信息");
					break;
				case CHAT_TYPE_VIDEO:
					xdebug("视频信息");
					break;
				case CHAT_TYPE_EMOJI:
					xdebug("表情信息");
					break;
	    }
			break;
		case TYPE_GUYCHAT:
			coapi_player_start(audio->toneurl, audio->audiourl);
			break;
		case TYPE_TIMER:
			coapi_player_start(audio->toneurl, audio->audiourl);
			break;
		case TYPE_FUNCHUB:
			coapi_player_start(audio->toneurl, audio->audiourl);
			break;
		case TYPE_PUSHTTS:
			coapi_player_start(audio->toneurl, audio->audiourl);
			break;
		default:
			break;
    }

    return;
}
/*
 * @brief OTA回调
 * @return  
 */
static void ota_callback(ota_info* ota, int status)
{
    if (ota == NULL) {
		return;
	}

#ifdef CONF_COMM_DEBUG
    xdebug("\nstatus: %d", status);
    xdebug("ota->action: %d", ota->action);
    xdebug("ota->endflag: %d", ota->endflag);
    xdebug("ota->mode: %d", ota->mode);
    xdebug("ota->offset: %d", ota->offset);
    xdebug("ota->size: %d", ota->size);
    xdebug("ota->data: %s", ota->data);
    xdebug("ota->md5: %s", ota->md5);
    xdebug("ota->version: %s\n", ota->version);
    xdebug("ota->detail: %s\n", ota->detail);
    xdebug("ota->appkey: %s\n", ota->appkey);
    xdebug("ota->devid: %s\n", ota->devid);
#endif

    if (ota->action == OTA_ACTION_NEW_VERSION) {
	/**
	 * 检查到新版本
	 * 新的版本号: ota->version
	 */
    } else if (ota->action == OTA_ACTION_NO_NEW_VERSION) {
	/* 无升级版本,当前版本是最新的版本 */
    } else if (ota->action == OTA_ACTION_LOAD_PKG) {
	/* 处理升级包,下发OTA升级包数据 */
    } else {
	/* null */
    }

    return;
}
/*
 * @brief json回调
 * @return  
 */
static void json_callback(char* str, int len)
{
    if (str == NULL) {
		return;
	}

#ifdef CONF_COMM_DEBUG
    xdebug("JSON: %s", str);
#endif

    return;
}

static void media_callback(media_info* media, int status)
{
    if (media == NULL) {
		return;
	}

#ifdef CONF_COMM_DEBUG
    xdebug("status: %d", status);
    xdebug("media mode: %d", media->mode);
    xdebug("media position: %d", media->position);
    xdebug("media status: %d", media->status);
    xdebug("media action: %d", media->action);
#endif

    return;
}
 
/*
 * @brief 功能集回调
 * @return  
 */
static void funchub_callback(funchub_info* info)
{
    switch (info->func) {
		case  FUNC_ID_ECI_WEATHER:
			break;
		case FUNC_ID_ECI_DATE:
			break;
		case FUNC_ID_AREQ_STORY:
		case FUNC_ID_AREQ_SONG:
		case FUNC_ID_AREQ_ENGLISH:
		case FUNC_ID_AREQ_POETRY:
		case FUNC_ID_AREQ_SINOLOGY:
		case FUNC_ID_AREQ_HABIT:
			break;
		default:
			break;
    }
}
/*
 * @brief 通用初始化
 * @return  
 */
void coapi_comm_init(void)
{
    coapi_sync_init(sync_callback);
    coapi_timer_init(timer_callback, TIMER_MODE_A);
    coapi_audio_init(audio_callback);
    coapi_json_init(json_callback);
    coapi_wireless_init(wireless_callback);
    coapi_media_init(media_callback);
    coapi_funchub_init(funchub_callback);
    coapi_dev_ctrl_init();
}
/*
 * @brief 通用反初始化
 * @return  
 */
int coapi_comm_deinit(void)
{
    coapi_dev_ctrl_deinit();
    coapi_funchub_deinit();
    coapi_media_deinit();
    /* coapi_wireless_deinit(); */ 
    coapi_audio_deinit();
    /* coapi_led_deinit(); */
    coapi_timer_deinit();
    coapi_sync_deinit();

    return 0;
}
